package org.mtdownload.utils;

import java.util.Enumeration;
import java.util.List;

/**
 * This enumeration provides an enumeration that goes in a circular way, that is, when it reaches the
 * last element of the list provided, it starts from the beggining. The hasMoreElements method always
 *  returns true.
 * @author sergiu
 */
public class CircularEnumeration<E> implements Enumeration {

	/**The list*/
	private List<? extends E> list=null;
	/**The current index*/
	private int index=0;
	
	/**
	 * Empty constructor
	 * @param list
	 */
	public CircularEnumeration() {
		/*nothing here*/
	}

	/**
	 * Constructor that takes as an argument the List on top of which this enumeration is based
	 * @param list
	 */
	public CircularEnumeration(List<? extends E> list) {
		setList(list);
	}

	public void setList(List<? extends E> list){
		if(list==null){
			throw new InternalError("The supplied argument is null.");
		}
		this.list=list;
		index=0;
	}
	/**
	 * We always have more elements, thus this method should never be called
	 */
	public boolean hasMoreElements() {
		throw new InternalError("Doesn't make any sense to call hasMoreElements method in this enumeration");
	}

	public E nextElement() {
		if(index>=list.size()){
			index=0;
		}
		return list.get(index++);
	}

	public void resetIndex(){
		index=0;
	}
}
